﻿CREATE PROCEDURE temp.s_RATExByPaymentFactor AS
DECLARE
	@PF float,@PmtsPerYear tinyint,@Term smallint,@OpenDate smalldatetime,@FstDueDate smalldatetime,@BaseDays smallint
SELECT @PF = 12000/248.81 ,@PmtsPerYear = 12,@Term=24,@OpenDate='1/1/2008',@FstDueDate='1/30/2008',@BaseDays=365

DECLARE @FNP int,@ODF float,@PMT float
DECLARE @PFx float/*Payment Factor*/

SELECT @FNP=PeriodsToFstPmt,@ODF=OddDaysFactor FROM dbo.LoanBreakDown(0,0,@PmtsPerYear,@Term,@OpenDate,@FstDueDate,@BaseDays)

DECLARE @PR numeric(38,30) ,@PRx  numeric(38,7)/*Periodic Rate*/SELECT @PR = 0, @PRx = .1/@PmtsPerYear

WHILE @PR <> ROUND(@PRx,7) BEGIN
	PRINT dbo.sprint3('PR:%s,PRx:%s,Rate:%s',@PR,@PRx,ROUND(@PRx,7)*@PmtsPerYear)
	SET @PR = @PRx
	SET @PFx = ((1.0-1.0/POWER((1.0+@PRx),@Term))/@PRx)*((POWER((1.0+@PRx),(1.0-@FNP)))/(1.0+(@PRx*@ODF)))
	SET @PRx = @PRx/@PF*@PFx
END

PRINT (ROUND(@PRx,7)*@PmtsPerYear)

